package models

import (
	"time"
	"log"
	db "goblog/database"
	"goblog/helpers"
)

type Xx struct {
	Id   string
	Name string
	Age  int
}

type User struct {
	Id string `json:"id" form:"id"`
	Name string `json:"name" form:"name"`
	Password string `json:"password" form:"password"`
	Age int `json:"age" form:"age"`
	Sex int `json:"sex" form:"sex"`
	Email string `json:"email" form:"email"`
	CreateTime time.Time `json:"createTime" form:"createTime"`
	UpdateTime time.Time `json:"updateTime" form:"updateTime"`
	DelFlag int `json:"delFlag" form:"delFlag"`
}

func AddUser(user *User) bool {
	rows, err := db.Orm.Insert(user)
	if err != nil {
		log.Println(err)
		return false
	}
	if rows == 0 {
		return false
	}
	return true
}

//删除(根据id删除)
func DeleteUserById(id string)  bool {
	user := User{
		Id: id,
	}
	rows,err := db.Orm.Delete(&user)
	if err != nil {
		log.Println(err)
		return false
	}
	if rows == 0 {
		return false
	}
	return true
}

//更新
func UpdateUser(user *User) bool {
	//Update(bean interface{}, condiBeans ...interface{}) bean是需要更新的bean,condiBeans是条件
	rows,err := db.Orm.Update(user,User{Id:user.Id})
	if err != nil {
		log.Println(err)
		return false
	}
	if rows > 0 {
		return true
	}
	return false
}

//查询所有
func GetUsers() []User {
	var users []User
	db.Orm.SQL(helpers.SSql("select * from $S.user")).Find(&users)
	return users
}

func GetUserByNameAndPwd(name,pwd string) (User,error) {
	var user User
	_, err := db.Orm.Where(helpers.SSql("$S.user.name = ? and $S.user.password = ?"), name,pwd).Get(&user)
	return user,err
}

func GetUserById(id string) User {
	var user User
	db.Orm.Where(helpers.SSql("$S.user.id = ?"), id).Get(&user)
	return user
}

//条件查询
func GetUsersById(id string) []User {
	var users []User
	db.Orm.Where(helpers.SSql("$S.user.id=?"), id).Find(&users)
	return users
}

/**
分页查询  页数  每页条数
 */
func GetPageUsers(pageNum,pageSize int) []User {
	var users []User
	err := db.Orm.Limit(pageSize,(pageNum - 1) * pageSize).Find(&users)
	if err != nil {
		return nil
	}
	return users
}

//利用sql操作
func ExecBySQL(sql string) bool {
	result,err := db.Orm.Exec(sql)
	if err != nil {
		log.Println(err)
		return false
	}
	rows,err :=result.RowsAffected()
	if err == nil && rows >0 {
		return true
	}
	return false
}